﻿module RPG {
    export class WorldMap extends Phaser.State {
        worldMap: Phaser.Tilemap;
        outlineGroup: Phaser.Group;
        levels: Phaser.Group;

        preload() {
            this.levels = this.game.add.group();
        }

        create() {
            this.worldMap = this.game.add.tilemap('world_map');
            this.worldMap.addTilesetImage('Terrain', 'terrain_tiles');
            this.worldMap.addTilesetImage('Water', 'water_tiles');
            this.worldMap.addTilesetImage('Mountains', 'mountain_tiles');

            

            var worldLayer = this.worldMap.createLayer('Ocean');
            worldLayer.scale.x = 1;
            worldLayer.scale.y = 1;
            worldLayer.resizeWorld();
            this.worldMap.createLayer('Sea Level');
            this.worldMap.createLayer('Features');
            this.worldMap.createLayer('Rivers');
            this.worldMap.createLayer('Vegetation');
            this.worldMap.createLayer('Forest');
            this.worldMap.createLayer('Caves');
            this.worldMap.createLayer('Roads');
            this.worldMap.createLayer('Structures');

            //Build Level Outlines

            //Level1
            
            //Level 1 outline
            this.createOutline([
                [37, 234], [242, 234], [312, 321], [306, 567], [251, 567],
                [191, 481], [150, 475], [144, 458], [111, 482], [98, 493],
                [60, 490], [26, 441], [12, 430], [64, 285]
            ], 'Level1');
        }

        update() {

        }


        clickMap(sprite:Phaser.Graphics) {
            this.game.state.start(sprite.name, true, false);
        }


        createOutline(linePoints: number[][], stateName: string) {
            // set a fill and line style
            var initX = linePoints[0][0];
            var initY = linePoints[0][1];

            var outline = this.game.add.graphics(0, 0);
            outline.beginFill(0xFFFFFF, 0);
            outline.lineStyle(0, 0x000000, 1);

            outline.moveTo(initX, initY);
            for (var i = 1; i < linePoints.length; i++) {
                outline.lineTo(linePoints[i][0], linePoints[i][1]);
            }

            outline.boundsPadding = 0;
            outline.endFill();
            outline.visible = true;
            var texture = outline.generateTexture();
            outline.hitArea = outline.getBounds();
            
            outline.inputEnabled = true;
            outline.input.priorityID = 1;
            outline.name = stateName;

            outline.events.onInputDown.add(this.clickMap, this, null, outline);
        }

        render() {
            //this.game.debug.inputInfo(32, 32); //Uncomment for DEBUG
        }
    }
}

